#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
天气信息获取模块
支持多个天气API提供商
"""

import requests
import logging
from typing import Dict, Any, Optional


class WeatherAPI:
    """天气API处理类"""
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化天气API
        
        Args:
            config: 天气配置信息
        """
        self.config = config
        self.api_key = config.get('api_key', '')
        self.city = config.get('city', '北京')
        self.provider = config.get('api_provider', 'openweathermap')
        self.logger = logging.getLogger(__name__)
        
    def get_weather(self) -> Optional[Dict[str, Any]]:
        """获取天气信息"""
        try:
            if self.provider == 'openweathermap':
                return self._get_openweathermap_weather()
            elif self.provider == 'free':
                return self._get_free_weather()
            else:
                self.logger.error(f"不支持的天气API提供商：{self.provider}")
                return None
        except Exception as e:
            self.logger.error(f"获取天气信息失败：{e}")
            return None
    
    def _get_openweathermap_weather(self) -> Optional[Dict[str, Any]]:
        """
        通过OpenWeatherMap API获取天气信息
        需要注册API Key: https://openweathermap.org/api
        """
        if not self.api_key or self.api_key == 'YOUR_WEATHER_API_KEY':
            self.logger.warning("OpenWeatherMap API Key未配置，尝试使用免费API")
            return self._get_free_weather()
        
        try:
            url = "http://api.openweathermap.org/data/2.5/weather"
            params = {
                'q': self.city,
                'appid': self.api_key,
                'units': 'metric',
                'lang': 'zh_cn'
            }
            
            response = requests.get(url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            return {
                'city': data['name'],
                'description': data['weather'][0]['description'],
                'temperature': round(data['main']['temp']),
                'feels_like': round(data['main']['feels_like']),
                'humidity': data['main']['humidity'],
                'pressure': data['main']['pressure'],
                'wind_speed': data.get('wind', {}).get('speed', 0),
                'suggestion': self._get_weather_suggestion(data['weather'][0]['main'], data['main']['temp'])
            }
            
        except requests.exceptions.RequestException as e:
            self.logger.error(f"OpenWeatherMap API请求失败：{e}")
            return self._get_free_weather()
        except KeyError as e:
            self.logger.error(f"OpenWeatherMap API响应格式错误：{e}")
            return self._get_free_weather()
    
    def _get_free_weather(self) -> Optional[Dict[str, Any]]:
        """
        使用免费天气API获取天气信息
        使用天气API（无需注册）
        """
        try:
            # 使用免费的天气API (可能需要根据实际可用的API调整)
            url = "http://wttr.in/"
            params = {
                'format': 'j1',
                'lang': 'zh'
            }
            
            response = requests.get(f"{url}{self.city}", params=params, timeout=15)
            
            if response.status_code == 200:
                data = response.json()
                current = data['current_condition'][0]
                
                return {
                    'city': self.city,
                    'description': current.get('lang_zh', [{}])[0].get('value', current.get('weatherDesc', [{}])[0].get('value', '未知')),
                    'temperature': int(current['temp_C']),
                    'feels_like': int(current['FeelsLikeC']),
                    'humidity': int(current['humidity']),
                    'pressure': int(current['pressure']),
                    'wind_speed': int(current['windspeedKmph']),
                    'suggestion': self._get_weather_suggestion_by_temp(int(current['temp_C']))
                }
            else:
                # 如果免费API也失败，返回模拟数据
                return self._get_mock_weather()
                
        except Exception as e:
            self.logger.warning(f"免费天气API请求失败：{e}，使用模拟数据")
            return self._get_mock_weather()
    
    def _get_mock_weather(self) -> Dict[str, Any]:
        """获取模拟天气数据（作为备用方案）"""
        import random
        from datetime import datetime
        
        # 根据月份生成合理的温度范围
        month = datetime.now().month
        if month in [12, 1, 2]:  # 冬季
            temp = random.randint(-5, 10)
        elif month in [3, 4, 5]:  # 春季
            temp = random.randint(10, 25)
        elif month in [6, 7, 8]:  # 夏季
            temp = random.randint(20, 35)
        else:  # 秋季
            temp = random.randint(10, 25)
        
        weather_conditions = ['晴天', '多云', '阴天', '小雨', '晴转多云']
        
        return {
            'city': self.city,
            'description': random.choice(weather_conditions),
            'temperature': temp,
            'feels_like': temp + random.randint(-3, 3),
            'humidity': random.randint(40, 80),
            'pressure': random.randint(1000, 1020),
            'wind_speed': random.randint(0, 15),
            'suggestion': self._get_weather_suggestion_by_temp(temp) + "\n（注意：当前为模拟天气数据，请以实际天气为准）"
        }
    
    def _get_weather_suggestion(self, weather_main: str, temperature: float) -> str:
        """根据天气状况生成建议"""
        suggestions = []
        
        # 根据天气类型添加建议
        weather_main = weather_main.lower()
        if 'rain' in weather_main or 'drizzle' in weather_main:
            suggestions.append("今天有雨，记得带伞！")
        elif 'snow' in weather_main:
            suggestions.append("今天下雪，注意保暖和路面湿滑！")
        elif 'cloud' in weather_main:
            suggestions.append("今天多云，适合外出活动。")
        elif 'clear' in weather_main:
            suggestions.append("今天天气晴朗，心情愉快！")
        elif 'fog' in weather_main or 'mist' in weather_main:
            suggestions.append("今天有雾，出行注意安全。")
        
        # 根据温度添加建议
        suggestions.append(self._get_weather_suggestion_by_temp(temperature))
        
        return " ".join(suggestions)
    
    def _get_weather_suggestion_by_temp(self, temperature: float) -> str:
        """根据温度生成穿衣建议"""
        try:
            if temperature <= 0:
                return "气温较低，建议穿厚外套和保暖衣物。"
            elif temperature <= 10:
                return "气温偏冷，建议穿外套或毛衣。"
            elif temperature <= 20:
                return "气温适中，建议穿长袖衬衫或薄外套。"
            elif temperature <= 30:
                return "气温舒适，建议穿短袖或薄长袖。"
            else:
                return "气温较高，建议穿轻薄透气的衣物，注意防暑。"
        except UnicodeEncodeError:
            return "请根据天气情况适当穿衣。"


# 测试函数
def test_weather_api():
    """测试天气API功能"""
    config = {
        'api_key': 'YOUR_WEATHER_API_KEY',
        'city': '北京',
        'api_provider': 'free'
    }
    
    weather_api = WeatherAPI(config)
    weather_info = weather_api.get_weather()
    
    if weather_info:
        print("天气信息获取成功：")
        for key, value in weather_info.items():
            print(f"{key}: {value}")
    else:
        print("天气信息获取失败")


if __name__ == "__main__":
    test_weather_api()